import { EventType, MenuId } from '@shared/index'
import { sendMessage } from './postMessage'

const list: { id: MenuId; title: string; documentUrlPatterns?: string[] }[] = [
  {
    id: MenuId.OPTIONS,
    title: '配置'
  },
  {
    id: MenuId.DOWNLOAD,
    title: '下载当前视频'
    // documentUrlPatterns: ['https://www.douyin.com/user/*', 'https://www.douyin.com/video/*']
  },
  {
    id: MenuId.PARSE_LIST,
    title: '解析视频列表'
    // documentUrlPatterns: ['https://www.douyin.com/user/*']
  }
]

chrome.runtime.onInstalled.addListener(() => {
  const parentId = chrome.contextMenus.create({
    id: 'root',
    title: '下载管理',
    // documentUrlPatterns: ['https://www.douyin.com/*'],
    documentUrlPatterns: ['https://developer.chrome.com/*']
  })

  list.forEach(({ id, title, documentUrlPatterns }) => {
    chrome.contextMenus.create({ id, parentId, title, documentUrlPatterns })
  })
})

chrome.contextMenus.onClicked.addListener((info, tab) => {
  console.log({ info, tab })
  switch (info.menuItemId) {
    case MenuId.OPTIONS: {
      chrome.runtime.openOptionsPage()
      break
    }
    case MenuId.DOWNLOAD:
    case MenuId.PARSE_LIST: {
      sendMessage(tab?.id!, { type: EventType.CONTEXT_MENU, data: info.menuItemId })
      break
    }
  }
})
